package com.hisense.ovcloud.commons.configs.validator;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.web.server.ResponseStatusException;
import reactor.core.publisher.SynchronousSink;

public class BaseRouterConfiguration {
    public <T> void validate(SynchronousSink<T> sink, Validator validator, T body, Class<T> clazz){
        Errors errors = new BeanPropertyBindingResult(body, clazz.getName());
        validator.validate(body, errors);

        if (errors.getAllErrors().isEmpty()) {
            sink.next(body);
        } else {
            sink.error(new ResponseStatusException(
                    HttpStatus.BAD_REQUEST,
                    errors.getAllErrors().getFirst().toString()));
        }
    }
}
